#include "VideoCanvas.h"
#include <QPainter>
#include <QPaintEngine>
#include "CvxWin32.h"
#include "MainWindowBase.h"
#include "process.h"
#include <iostream>
CVideoCanvas::CVideoCanvas(OCEANUI::CMainWindowBase* parent):
	CCentralCanvasBase(parent),
	pCapture_(NULL),
	pCurrentImg_(NULL)
{
	 setAttribute(Qt::WA_NoBackground);
	 resize(800,600); 
	 setVisible(true);
	 bool connectResult = connect(this,SIGNAL(SigUpdate()),this,SLOT(repaint ()),Qt::ConnectionType::QueuedConnection);
	 assert(connectResult);
	 InitializeCriticalSection(&imagelock_);
}

CVideoCanvas::~CVideoCanvas(void)
{
}

bool CVideoCanvas::play()
{
	if (NULL == pCapture_)
	{
		return false;
	}

	IplImage* frame = 0;
	int i, k, c;

	frame = cvQueryFrame( pCapture_ );

	return true;

}

bool CVideoCanvas::pause()
{
	return true;
}

bool CVideoCanvas::resume()
{
	return true;
}

bool CVideoCanvas::stop()
{
	return true;
}

void __cdecl videoPlayThreadCallBack(void* pData)
{
	CVideoCanvas* pVideo = reinterpret_cast<CVideoCanvas*>(pData);
	CvCapture* pCapture = pVideo ->getCapture();
	bool bRunning = true;
	IplImage* pImg = NULL;
	int waitTime = cvRound((1/pVideo->fps_) * 1000);
	while ( bRunning)
	{
		pImg= cvQueryFrame(pCapture);
		if (NULL == pImg)
		{
			bRunning = false;
			break;
		}
		IplImage* pImgCpy = cvCloneImage(pImg);
		//maybe it's too slow
		//TODO: record pannel want to hook this event
		OCEANUI::CMainWindowBase::gInstance().onEventChanged(pImg,pVideo);
		pVideo->syncVideoImage(pImgCpy);
		Sleep(waitTime);
		//std::cout << xx << std::endl;
	}
}

void CVideoCanvas::initData( void* pData )
{
	 
	pCapture_ = reinterpret_cast<CvCapture*>(pData);
	if (NULL == pCapture_)
	{
		return;
	}
	fps_ = cvGetCaptureProperty(pCapture_,CV_CAP_PROP_FPS);
	_beginthread(videoPlayThreadCallBack,0,this);
	 
}

void CVideoCanvas::paintEvent( QPaintEvent *event )
{
	if (NULL == pCurrentImg_)
	{
		return;
	}
	QPainter painter(this);
	QRect qrc = this->geometry();
	ResourceLocker lock(&imagelock_);
	CvRect rc =cvRect(qrc.x(),qrc.y(),pCurrentImg_->width,pCurrentImg_->height);
	CvxWin32::DrawToHDC(pCurrentImg_,painter.paintEngine()->getDC(),&rc);
}

void CVideoCanvas::syncVideoImage( IplImage* pImg )
{
	ResourceLocker lock(&imagelock_);
	if (NULL != pCurrentImg_)
	{
		cvReleaseImage(&pCurrentImg_);
	}
	pCurrentImg_ = pImg;
	emit SigUpdate();
}